<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>Promise原理</title>
	</head>
	<body>
        <h1>Promise原理</h1>
	</body>
    <script type="text/javascript">
        

        // function P(fn) {
        //     var state = 'pending',
        //         value = null,
        //         callbacks = [];

        //     this.then = function (onFulfilled) {
        //         if (state === 'pending') {
        //             callbacks.push(onFulfilled);
        //             return this;
        //         }
        //         onFulfilled(value);
        //         return this;
        //     };

        //     function resolve(newValue) {
        //         value = newValue;
        //         state = 'fulfilled';
        //         setTimeout(function () {
        //             callbacks.forEach(function (callback) {
        //                 callback(value);
        //             });
        //         }, 0);
        //     }

        //     fn(resolve);
        // }

        function P(fn) {
            var state = 'pending',
                value = null,
                callbacks = [];

            this.then = function (onFulfilled) {
                return new P(function (resolve) {
                    handle({
                        onFulfilled: onFulfilled || null,
                        resolve: resolve
                    });
                });
            };

            function handle(callback) {
                if (state === 'pending') {
                    callbacks.push(callback);
                    return;
                }
                //如果then中没有传递任何东西
                if(!callback.onFulfilled) {
                    callback.resolve(value);
                    return;
                }

                var ret = callback.onFulfilled(value);
                callback.resolve(ret);
            }

            
            function resolve(newValue) {
                if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
                    var then = newValue.then;
                    if (typeof then === 'function') {
                        then.call(newValue, resolve);
                        return;
                    }
                }
                state = 'fulfilled';
                value = newValue;
                setTimeout(function () {
                    callbacks.forEach(function (callback) {
                        handle(callback);
                    });
                }, 0);
            }

            fn(resolve);
        }

        const p = new P((resolve)=>{
            resolve('aaaaa')
        }).then((data)=>{
            return new P((resolve)=>{
                resolve(`${data}bbb`)
            })
        }).then((data)=>{
            console.log('data',data)
        })


	</script>
</html>
